from flask import Flask, request, jsonify
import uuid
from task_manager import add_task, task_status

app = Flask(__name__)

@app.route('/api/v1/tasks/submit', methods=['POST'])
def submit_task():
    """
    接收任务提交请求。
    """
    print("\n收到任务提交请求")
    data = request.json
    print(f"请求数据: {data}")
    
    image_dir = data.get("image_dir")
    output_path = data.get("output_path")
    mode = data.get("mode", "quick")

    if not image_dir or not output_path:
        print("错误：缺少必要参数")
        return jsonify({"error": "Missing required parameters"}), 400

    task_id = str(uuid.uuid4())
    print(f"生成任务ID: {task_id}")
    
    task_data = {
        "image_dir": image_dir,
        "output_path": output_path,
        "mode": mode
    }

    result = add_task(task_id, task_data)
    if "error" in result:
        print(f"添加任务失败: {result['error']}")
        return jsonify(result), 400

    print(f"任务添加成功: {result}\n")
    return jsonify(result), 200

# @app.route('/api/v1/tasks/status/<task_id>', methods=['GET'])
# def get_task_status(task_id):
#     """
#     查询任务状态接口。
#     """
#     if task_id not in task_status:
#         return jsonify({"error": "Task not found"}), 404
#     return jsonify(task_status[task_id])

@app.route('/api/v1/tasks/output/<task_id>', methods=['DELETE'])
def delete_task_output(task_id):
    """
    删除任务输出文件接口。
    """
    print(f"\n收到删除请求，任务ID: {task_id}")
    print(f"当前任务状态: {task_status.get(task_id)}")
    
    if task_id not in task_status:
        print(f"错误：任务不存在 {task_id}")
        return jsonify({"error": "任务不存在"}), 404
    
    try:
        import os
        import shutil
        output_path = task_status[task_id].get('result_path')
        print(f"尝试删除目录路径: {output_path}")
        
        if output_path and os.path.exists(output_path):
            # 使用shutil.rmtree删除整个目录
            shutil.rmtree(output_path)
            task_status[task_id]['result_path'] = None
            print(f"成功删除输出目录: {output_path}")
            return jsonify({"message": "输出目录已成功删除"}), 200
        else:
            print(f"错误：输出目录不存在 {output_path}")
            return jsonify({"error": "输出目录不存在"}), 404
    except PermissionError as pe:
        error_msg = f"删除目录时权限不足: {str(pe)}"
        print(error_msg)
        return jsonify({"error": error_msg}), 403
    except Exception as e:
        error_msg = f"删除目录时发生错误: {str(e)}"
        print(error_msg)
        return jsonify({"error": error_msg}), 500

if __name__ == '__main__':
    print("\n=== UAV任务处理服务启动 ===")
    print("监听端口: 5000")
    print("等待任务提交...\n")
    app.run(debug=True)
